package controller_book

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"tools-api/src/common/utils"
	"tools-api/src/jcj/model"
	"tools-api/src/jcj/service/service_book"
	"tools-api/src/routes/request"
	"tools-api/src/routes/response"
)

// DetailAdd 添加支出/收入
func DetailAdd(ctx *gin.Context) {
	var req = struct {
		Id         int64   `json:"id"`
		Type       int     `json:"type"`
		Money      float64 `json:"money"`
		Remark     string  `json:"remark"`
		Date       string  `json:"date"`
		TypesId    int64   `json:"types_id"`
		AccountsId int64   `json:"accounts_id"`
	}{}
	_ = ctx.ShouldBindBodyWith(&req, binding.JSON)
	if req.Type != 1 && req.Type != 2 {
		response.Fail(ctx, "参数错误")
		return
	}
	if req.TypesId <= 0 {
		response.Fail(ctx, "请选择类别")
		return
	}
	if req.Money == 0 {
		response.Fail(ctx, "请输入具体金额")
		return
	}
	if req.Date == "" {
		response.Fail(ctx, "请选择日期")
		return
	}
	uuid := request.GetCurrentUser(ctx)
	book := service_book.GetCurrentBook(uuid)
	if book.Id == 0 {
		response.Fail(ctx, "请选择当前账本")
		return
	}
	detail := model.BookDetail{
		Id:         req.Id,
		Uuid:       uuid,
		BookId:     book.Id,        // 账本
		AccountsId: req.AccountsId, // 收支账户
		Type:       req.Type,
		Money:      req.Money,
		Date:       req.Date,
		TypesId:    req.TypesId,
		Remark:     req.Remark,
	}
	ok, msg := service_book.BookDetailAddOrUpdate(detail)
	if ok {
		response.SuccessMsg(ctx, msg)
	} else {
		response.Fail(ctx, msg)
	}
}

// DetailDelete 单个删除
func DetailDelete(ctx *gin.Context) {
	id := utils.Str2Int64(ctx.Param("id"))
	if id <= 0 {
		response.Fail(ctx, "参数错误")
		return
	}
	err := service_book.BookDetailDelete(request.GetCurrentUser(ctx), id)
	if err != nil {
		response.Fail(ctx, "删除失败")
		return
	}
	response.SuccessMsg(ctx, "删除成功")
}

// DetailList 明细列表
func DetailList(ctx *gin.Context) {
	date := ctx.Query("date")
	if date == "" {
		response.Fail(ctx, "参数错误")
		return
	}
	uuid := request.GetCurrentUser(ctx)
	book := service_book.GetCurrentBook(uuid)
	if book.Id == 0 {
		response.Fail(ctx, "请选择当前账本")
		return
	}
	result := service_book.GetDetailList(uuid, book.Id, date, book.MonthStart)
	response.Success(ctx, result)
}
